<?php

namespace App\Admin\Forms;
use App\Admin\Services\PackageImportService;
use Dcat\EasyExcel\Excel;
use Dcat\Admin\Widgets\Form;

/**
 * Created by PhpStorm.
 * User: 共赢岛
 * Date: 2024/1/25
 * Time: 9:05
 */
class PackageUsedImport extends Form
{
    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return \Dcat\Admin\Http\JsonResponse
     */
    public function handle(array $input)
    {
        // 获取上传的文件路径
        $file_path = storage_path('app/public' . $input['import_file']);
        // 如果用的是maatwebsite/excel或者其他, 把读取数据这一步改改就好了
        // 读取excel文件
        $data = Excel::import($file_path)->toArray();

        $sheet = $data['Sheet1'];

        foreach ($sheet as $key => $value) {
            $value['created_at'] = $value['created_at']->format('Y-m-d H:i:s');
            PackageImportService::attrUsed($value);
        }

        return $this->response()->success('导入成功！')->refresh();
    }
    /**
     * Build a form here.
     */
    public function form()
    {
        // 禁用重置表单按钮
        $this->disableResetButton();
        // 文件上传
        $this->file('import_file', ' ')
            ->disk('public')
            ->accept('xls,xlsx')
            ->uniqueName()
            ->autoUpload()
            ->move('/import')
            ->help('支持xls,xlsx');
    }
}